package com.usoft;

import com.usoft.grpc.example.helloworld.GreeterGrpc;
import com.usoft.grpc.example.helloworld.HelloRequest;
import com.usoft.grpc.example.helloworld.HelloResponse;
import com.usoft.grpc.example.search.SearchRequest;
import com.usoft.grpc.example.search.SearchResponse;
import com.usoft.grpc.example.search.SearchServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by xinxingegeya on 16/1/2.
 */
public class MultiServiceClient {

    private static final Logger logger = Logger
        .getLogger(MultiServiceClient.class.getName());

    private String address = "127.0.0.1";
    private int port = 8888;

    private ManagedChannel channel;
    private SearchServiceGrpc.SearchServiceBlockingStub searchBlockingStub;
    private SearchServiceGrpc.SearchServiceStub asyncStub;

    private GreeterGrpc.GreeterBlockingStub greeterBlockingStub;
    private GreeterGrpc.GreeterStub greeterStub;

    @Before
    public void setup() {
        channel = ManagedChannelBuilder.forAddress(address, port)
            .usePlaintext(true).build();
        searchBlockingStub = SearchServiceGrpc.newBlockingStub(channel);
        asyncStub = SearchServiceGrpc.newStub(channel);

        greeterBlockingStub = GreeterGrpc.newBlockingStub(channel);
        greeterStub = GreeterGrpc.newStub(channel);

    }

    @After
    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    @Test
    public void testSearch() {
        try {
            SearchRequest request = SearchRequest.newBuilder().setPageNumber(10)
                .setResultPerPage(10).build();
            SearchResponse response = searchBlockingStub
                .searchWithSimpleRpc(request);
            logger.info("search result: " + response.toString());
        } catch (RuntimeException e) {
            logger.log(Level.WARNING, "RPC failed", e);
            return;
        }
    }

    @Test
    public void testGreeter() {

        HelloRequest request = HelloRequest.newBuilder().setName("liyanxin")
            .build();
        HelloResponse response = greeterBlockingStub.sayHello(request);

        System.out.println(response.getMessage());
    }

}
